#!/usr/local/bin/python3.6
# coding:utf-8
# @Time    : 2019/11/1 17:35
# @Author  : ZhangBing
# @Email   : 18829272841@163.com
# @File    : view.py
# @Software: PyCharm
from flask import request, make_response, session, Blueprint, render_template, redirect, url_for
import bcrypt
from modules import User
from exts import db
from utils import getlogger, login_auth

log = getlogger('user')
user = Blueprint('user', __name__)


@user.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        if request.is_json:  # 此处用于判断是否是json数据，若是json数据，则按照下述方式处理，否则是data-from数据，则按照对应方式处理
            data = request.json
        else:
            data = request.form
        email = data['email']
        q = User.query.filter(User.email == email)
        if q.count():
            query = q.first()
            if bcrypt.checkpw(data['password'].encode(), query.password.encode()):
                log.info('用户 {} 登陆成功'.format(email))
                session['id'] = q.first().id  # 设置会话配置
                return redirect(url_for('post.pub'))
            else:
                log.warning('用户{} 登陆失败'.format(email))
                return make_response('用户{} 登陆失败'.format(email), 405)
    return render_template('login.html')


@user.route('/reg', methods=["POST", "GET"])
def reg():
    if request.method == "POST":
        if request.is_json:
            data = request.json
        else:
            data = request.form
        query = User.query.filter(User.email == data['email'])
        if query.count():
            return make_response('邮箱{}已经被注册'.format(data['email']), 405)
        password = bcrypt.hashpw(data['password'].encode(), bcrypt.gensalt()).decode()  # 加盐处理
        user = User(data['email'], data['username'], password=password)
        try:
            db.session.add(user)
            db.session.commit()
            log.info("用户 {} 注册成功".format(user.username))
            session['id'] = user.id  # 设置会话配置,此处使用id进行处理
            # return jsonify(
            #     {
            #         "id": user.id
            #     }
            # )
            return redirect(url_for('base.index'))  # 此处是模块名加上index 构成返回结果
        except  Exception  as e:
            print(e)
            log.warning("用户 {} 注册失败".format(user.username), 405)
            return "注册失败"
    return render_template('reg.html')


if __name__ == "__main__":
    pass
